package realm.inorder.itmill.components.table;

import java.io.Serializable;
import java.util.Collection;
import java.util.Set;

import org.apache.log4j.Logger;

import com.itmill.toolkit.ui.Table;

public abstract class DefaultTableModel<T> extends Table implements TableModel<T> {

	private final Logger logger = Logger.getLogger(getClass());

	private Set<Object> selectedItemIds = null;

	private Serializable selectedItemId;
	
	public DefaultTableModel() {
		super();
		setImmediate(true);
		buildTable();
		this.addListener(getValueChangeListener());
	}

	public ValueChangeListener getValueChangeListener() {
		return new ValueChangeListener() {
			public void valueChange(
					com.itmill.toolkit.data.Property.ValueChangeEvent event) {
				
				if (isMultiSelect()) {
					selectedItemIds = (Set)event.getProperty().getValue();
				} else {
					if (event.getProperty().getValue() == null) {
						selectedItemId = null;
					} else {
//						selectedItem = (T)event.getProperty().getValue();
//						Item item = getItem(event.getProperty().getValue());
//						System.out.println("Item: "+item);
						selectedItemId = (Serializable)event.getProperty().getValue();
//						Collection itemPropertyIds = item.get
//						for (Object object : itemPropertyIds) {
//							logger.debug("Ids: "+object.toString());
//						}
					}
				}
			}
		};
	}

	protected void buildTable() {
		String[] columns = this.getColumnNames();

		for (int columnIndex = 0; columnIndex < columns.length; columnIndex++) {
			String column = columns[columnIndex];

			this.addContainerProperty(column, this.getColumnClass(columnIndex), "(Nenhum)");
			this.setColumnWidth(column, this.getColumnWidth(columnIndex));
		}
	}

	private void buildItem(T t) {
		int columnLength = getColumnNames().length;

		Object[] cols = new Object[columnLength];

		for (int columnIndex = 0; columnIndex < columnLength; columnIndex++) {
			Object propertyValue = this.getValueAt(t, columnIndex);

			cols[columnIndex] = propertyValue;
		}

		Object itemId = getBeanId(t);

		this.addItem(cols, itemId);
	}

	public void add(T t) {
		buildItem(t);
	}

	public void addAll(Collection<T> itens) {
		for (T t : itens) {
			add(t);
		}
	}
	
	public void setItems(Collection<T> itens) {
		removeAllItems();
		for (T t : itens) {
			add(t);
		}
	}

	public void rebuildTable() {
		buildTable();
	}

	public Set<Object> getSelectedItemIds() {
		return selectedItemIds;
	}

	public Serializable getSelectedItemId() {
		return selectedItemId;
	}

	public void setSelectedItemId(Serializable selectedItemId) {
		this.selectedItemId = selectedItemId;
	}

}
